//
//  NHTFunction.m
//  DevelopDemo
//
//  Created by NHT on 2024/6/7.
//

#import "NHTFunction.h"
#import <UIKit/UIKit.h>
#import <MediaPlayer/MediaPlayer.h>

#import <CoreLocation/CoreLocation.h>//定位
#import <ContactsUI/ContactsUI.h>//联系人
#import <AVFoundation/AVFoundation.h>//相机
#import <Photos/PHPhotoLibrary.h>//相册
#import <AVFoundation/AVFoundation.h>//麦克风
#import <UserNotifications/UserNotifications.h>//推送
//#import <CoreBluetooth/CoreBluetooth.h>//蓝牙
//#import <NHT_Push/NHTPushService.h>

@interface NHTFunction ()<AVSpeechSynthesizerDelegate,CLLocationManagerDelegate,AVAudioPlayerDelegate>

///是否是调试模式
@property (nonatomic,assign) BOOL  isDebugMode;

///声音播放
@property(nonatomic,strong)AVAudioPlayer *movePlayer;

#pragma mark---语音播报
/**语音播报*/
@property (nonatomic, strong) AVSpeechSynthesizer *synthesizeSpeech;
///是否循环重复播报
@property (nonatomic,assign) BOOL  repeatPlay;
///语音播报的内容
@property (nonatomic,copy) NSString  *speechText;
///语音播报的语言
@property (nonatomic,copy) NSString  *speechLanguage;
///控制声音变为最大
@property(nonatomic,strong) UISlider *volumeViewSlider;
///配置可以静音、后台播放
@property (nonatomic,assign) BOOL  setVoiceConfig;
///播放音频、语音播报的音量，默认最大，支持范围0-1
@property (nonatomic,assign) CGFloat volume;


#pragma mark---闪光灯、震动
///设备
@property (nonatomic,strong) AVCaptureDevice  *device;
///是否已经停止闪光灯
@property (nonatomic,assign) BOOL  needFlash;


///是否已经停止振动
@property (nonatomic,assign) BOOL  needShock;

#pragma mark---权限检查
///权限回调
@property (nonatomic,copy) void(^powerBlock)(NSInteger status);

///定位信息要使用成员变量否则会被arc提前释放一闪而过
@property (nonatomic, strong) CLLocationManager *locationManager;
/////蓝牙
//@property (nonatomic, strong) CBCentralManager *centralManager;


/// 音频播放
@property (nonatomic, strong) AVPlayer *avPlayer;

///是否重复播放
@property (nonatomic,assign) BOOL  needRepeatPlay;

@end

@implementation NHTFunction

+(instancetype)share{
    static NHTFunction *shareFunction = nil;
    static dispatch_once_t onceTokern;
    dispatch_once(&onceTokern, ^{
        shareFunction = [[super allocWithZone:NULL] init];
        shareFunction.volume = 1.0;
        shareFunction.setVoiceConfig = false;
        shareFunction.showRefuseAlert = true;
        shareFunction.refuseAlertShowCancel = true;
        shareFunction.isDebugMode = false;
        shareFunction.needRepeatPlay = false;
    });
    return shareFunction;
}
//用alloc返回也是唯一实例
+(id) allocWithZone:(struct _NSZone *)zone {
    return [NHTFunction share] ;
}
//对对象使用copy也是返回唯一实例
-(id)copyWithZone:(NSZone *)zone {
    return [NHTFunction share] ;//return _instance;
}
//对对象使用mutablecopy也是返回唯一实例
-(id)mutableCopyWithZone:(NSZone *)zone {
    return [NHTFunction share] ;
}

/// 设置调试模式
-(void)setDebugMode{
    self.isDebugMode = true;
}
#pragma mark---公用方法

/// 设置静音、后台能播放
-(void)updateConfigPlay{
    ///调整声音
    [UIView animateWithDuration:0.01 animations:^{
    } completion:^(BOOL finished) {
        [self.volumeViewSlider setValue:self.isDebugMode ? 0.4:self.volume animated:NO];
    }];
    
    if(!self.setVoiceConfig){
        self.setVoiceConfig = true;
        //后台播放
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionAllowBluetooth error:nil];
        //静音状态下播放
        [[AVAudioSession sharedInstance] setActive:YES error:nil];
    }
}

#pragma mark---打电话
/// 拨打电话
/// - Parameter phoneNumber: 电话号码
-(void)callPhone:(NSString *)phoneNumber{
    NSMutableString *strPhone=[[NSMutableString alloc]initWithFormat:@"tel:%@",phoneNumber];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:strPhone] options:@{} completionHandler:^(BOOL success) {
        
    }];
}

#pragma mark---播放音频文件

/// 播放网络音频
/// - Parameters:
///   - url: 文件地址
///   - repeatPlay: 是否重复
-(void)startPlayUrlAudio:(NSString *)url repeatPlay:(BOOL)repeatPlay{
    NSURL *audioUrl = [NSURL URLWithString:url];
    [self startPlayLast:audioUrl repeatPlay:repeatPlay];
}

/// 播放本地音频
/// - Parameters:
///   - filePath: 文件路径path
///   - repeatPlay: 是否重复
-(void)startPlayLocalAudio:(NSString *)filePath  repeatPlay:(BOOL)repeatPlay{
    NSURL *audioUrl = [NSURL fileURLWithPath:filePath];
    [self startPlayLast:audioUrl repeatPlay:repeatPlay];
}

/// 播放本地音频
/// - Parameters:
///   - name: 文件名称
///   - type: 文件类型
-(void)startPlayLocalAudio:(NSString *)name type:(NSString *)type repeatPlay:(BOOL)repeatPlay{
    NSString *filePath = [[NSBundle mainBundle] pathForResource:name ofType:type];
    [self startPlayLocalAudio:filePath repeatPlay:repeatPlay];
}
-(void)startPlayLast:(NSURL *)audioUrl repeatPlay:(BOOL)repeatPlay{
    self.needRepeatPlay = repeatPlay;
    [self updateConfigPlay];

    self.avPlayer=[[AVPlayer alloc] initWithURL:audioUrl];
    self.avPlayer.volume = self.isDebugMode ? 0.4:self.volume;
    //    //监控状态属性，注意AVPlayer也有一个status属性，通过监控它的status也可以获得播放状态
    //    [self.avPlayer.currentItem addObserver:self forKeyPath:@"status" options:(NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew) context:nil];
    
    //监控播放完成通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished) name:AVPlayerItemDidPlayToEndTimeNotification object:self.avPlayer.currentItem];
    [self.avPlayer seekToTime:CMTimeMakeWithSeconds(0, 1.0)];//设置开始播放时间
    [self.avPlayer play];
}

-(void)playbackFinished{
    //监控播放完成通知
    NSLog(@"播放完成");
    if(self.needRepeatPlay){
        [self.avPlayer seekToTime:CMTimeMakeWithSeconds(0, 1.0)];//设置开始播放时间
        [self.avPlayer play];
    }
}
///停止播放音频
-(void)stopPlayAudio{
    if(_avPlayer){
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.avPlayer pause];
            self->_avPlayer = nil;
        });
    }
}

#pragma mark---语音播报
/// 语音播报文字
/// - Parameters:
///   - text: 需要播报的文字
///   - repeatPlay: 是否需要重复播放
-(void)startChangeTextToSpeech:(NSString *)text repeatPlay:(BOOL)repeatPlay{
    [self startChangeTextToSpeech:text repeatPlay:repeatPlay language:@"zh-CN"];
}
/// 语音播报文字
/// - Parameters:
///   - text: 需要播报的文字
///   - repeatPlay: 是否需要重复播放
///   - language: 播放时的语言
-(void)startChangeTextToSpeech:(NSString *)text repeatPlay:(BOOL)repeatPlay language:(NSString *)language{
    [self stopChangeTextToSpeech];
    [self updateConfigPlay];
    
    self.repeatPlay = repeatPlay;
    self.speechText = text;
    self.speechLanguage = language;
    AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc]initWithString:self.speechText];
    AVSpeechSynthesisVoice *voice = [AVSpeechSynthesisVoice voiceWithLanguage:self.speechLanguage];//zh-TW   zh-CN  zh-HK
    utterance.voice = voice;
    utterance.volume = self.isDebugMode ? 0.4:self.volume;
    [self.synthesizeSpeech speakUtterance:utterance];
}
/// 设置语音播报的声音大小
/// - Parameter newVolume: 设置的声音
-(void)setChangeTextToSpeechVolume:(float)newVolume{
    if(newVolume < 0 || newVolume > 1){
        self.volume = 1;
    }else{
        self.volume = newVolume;
    }
}

/// 停止播放文字
-(void)stopChangeTextToSpeech{
    self.repeatPlay = false;
    if(_synthesizeSpeech){
        [_synthesizeSpeech stopSpeakingAtBoundary:AVSpeechBoundaryImmediate];
    }
}
-(AVSpeechSynthesizer *)synthesizeSpeech{
    if (!_synthesizeSpeech) {
        _synthesizeSpeech = [[AVSpeechSynthesizer alloc] init];
        _synthesizeSpeech.delegate = self;
    }
    return _synthesizeSpeech;
}
///播放完毕
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didFinishSpeechUtterance:(AVSpeechUtterance *)utterance API_AVAILABLE(ios(7.0), watchos(1.0), tvos(7.0), macos(10.14)) {
    if(self.repeatPlay){
        [self startChangeTextToSpeech:self.speechText repeatPlay:self.repeatPlay language:self.speechLanguage];
    }
}

-(UISlider*)volumeViewSlider{
    if (!_volumeViewSlider) {
        MPVolumeView *volumeView = [[MPVolumeView alloc] initWithFrame:CGRectMake(10, 50, 200, 4)];
        for (UIView* newView in volumeView.subviews) {
            if ([newView.class.description isEqualToString:@"MPVolumeSlider"]){
                _volumeViewSlider = (UISlider*)newView;
                break;
            }
        }
        _volumeViewSlider.frame= CGRectMake(-1000, -1000, 100, 10);
    }
    return _volumeViewSlider;
}

#pragma mark---闪光灯
-(void)startFlash{
    if(!self.needFlash){
        self.needFlash = true;
        [self openFlash];
    }
}
-(void)stopFlash{
    self.needFlash = false;
}

-(void)openFlash{
    NSLog(@"------闪光灯------");
    if(self.needFlash){
        AVCaptureSession *session = [[AVCaptureSession alloc] init];
        self.device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        if ([self.device hasFlash]) {
            [self.device lockForConfiguration:nil];//此处以一定要调用这个方法不然程序运行到这里会崩溃
            [self.device setTorchMode:AVCaptureTorchModeOn];
            [self.device setFlashMode:AVCaptureFlashModeOn];
            [self.device unlockForConfiguration];
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                [session startRunning];
            });
        }
        
        
        self.device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        if ([self.device hasFlash]) {
            [self.device lockForConfiguration:nil];//此处以一定要调用这个方法不然程序运行到这里会崩溃
            [self.device setTorchMode:AVCaptureTorchModeOff];
            [self.device setFlashMode:AVCaptureFlashModeOff];
            [self.device unlockForConfiguration];
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                [session stopRunning];
            });
        }
        session = nil;
        self.device = nil;
        
        [self performSelector:@selector(openFlash) withObject:nil afterDelay:0.5];
    }
}

#pragma mark---振动
/// 打开震动
-(void)startShock{
    if(!self.needShock){
        self.needShock = true;
        [self openShock];
    }
}
-(void)stopShock{
    self.needShock = false;
}
-(void)openShock{
    NSLog(@"------震动------");
    if (self.needShock) {
        //连续震动
        AudioServicesPlaySystemSoundWithCompletion(kSystemSoundID_Vibrate, ^{
        });
        [self performSelector:@selector(openShock) withObject:nil afterDelay:1];
    }
}
#pragma mark---跳转到指定APP在Appstore的页面
/// 跳转到指定APP在Appstore的页面
/// - Parameter appID: app的id
-(void)gotoAppStoreUpdate:(NSString *)appID{
    if((appID == nil || appID == NULL || [appID isKindOfClass:[NSNull class]] || [[appID stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length] ==0 )){
        NSLog(@"appid不能为空！！");
        return;
    }
    NSString *url = [NSString stringWithFormat:@"itms-apps://itunes.apple.com/app/id%@",appID];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url] options:@{} completionHandler:^(BOOL success) {
    }];
}
#pragma mark---权限检查部分
///推送权限，不会自动申请权限
-(void)checkIsHavePower_Push:(void (^)(NSInteger status))allowBlock{
    [[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
        UNAuthorizationStatus status = settings.authorizationStatus;
        if(status == UNAuthorizationStatusNotDetermined){
            //未申请未定义
            allowBlock(PowerStateUndefined);
        }else if(status == UNAuthorizationStatusDenied){
            // 拒绝
            if(self.showRefuseAlert){
                [self showAlert:@"您尚未授予本应用推送消息的权限，请前往设置"];
            }
            allowBlock(PowerStateRefuse);
        }else{
            //允许
            allowBlock(PowerStateAllow);
        }
    }];
}
#pragma mark---定位
-(void)checkIsHavePower_Location:(void (^)(NSInteger status))allowBlock{
    CLAuthorizationStatus authorizationStatu_Location =  [CLLocationManager authorizationStatus];
    /*
     kCLAuthorizationStatusNotDetermined 未选择
     kCLAuthorizationStatusRestricted  受限制
     kCLAuthorizationStatusDenied   已拒绝
     kCLAuthorizationStatusAuthorized 已经明确使用定位功能
     kCLAuthorizationStatusAuthorizedWhenInUse  在使用期间允许使用定位功能
     kCLAuthorizationStatusAuthorizedAlways        App始终允许使用定位功能
     */
    self.powerBlock = allowBlock;
    if (authorizationStatu_Location == kCLAuthorizationStatusRestricted
        || authorizationStatu_Location == kCLAuthorizationStatusDenied ) {
        //拒绝
        if(self.showRefuseAlert){
            [self showAlert:@"您尚未授予本应用使用定位功能的权限，请前往设置"];
        }
        allowBlock(PowerStateRefuse);
    }else if (authorizationStatu_Location == kCLAuthorizationStatusNotDetermined) {
        //第一次申请权限
        self.locationManager = [[CLLocationManager alloc]init];
        self.locationManager.delegate = self;
        [self.locationManager requestAlwaysAuthorization];
        [self.locationManager requestWhenInUseAuthorization];
    }else {
        //允许
        allowBlock(PowerStateAllow);
    }
}

-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{
    if(status == kCLAuthorizationStatusNotDetermined){
        //第一次申请权限
    }else if(status == kCLAuthorizationStatusRestricted
             || status == kCLAuthorizationStatusDenied){
        self.powerBlock(PowerStateRefuse);
    }else{
        self.powerBlock(PowerStateAllow);
    }
}

//#pragma mark---蓝牙
//-(CBCentralManager *)centralManager{
//    if (!_centralManager) {
//        /**
//         不能直接根据self.centralManager.state判断
//         因为无论是否允许使用过，首次获取到的都是CBManagerStateUnknown
//         CBCentralManagerDelegate
//         */
//        _centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
//    }
//    return _centralManager;
//}
/// 校验是否有--蓝牙权限，info.plist中添加--NSBluetoothAlwaysUsageDescription
/// - Parameter AllowBlock: 权限结果回调，包含授权框弹出后的结果回调
//-(void)centralManagerDidUpdateState:(CBCentralManager *)central{
//    /**
//     不能直接根据self.centralManager.state判断，因为无论是否允许使用过，首次获取到的都是CBManagerStateUnknown
//     如果当前手机的蓝牙处于关闭状态，第一次时系统会自动有个打开蓝牙的提示！
//     */
//    CBManagerState state = central.state;
//    if(state == CBManagerStateUnknown){
//        //未知，第一次使用
//        self.powerBlock(PowerStateUndefined);
//    }else if(state == CBManagerStateResetting){
//        //重置中
//        self.powerBlock(PowerStateBluetoothResetting);
//    }else if(state == CBManagerStateUnsupported){
//        //不支持
//        self.powerBlock(PowerStateBluetoothUnsupported);
//    }else if(state == CBManagerStateUnauthorized){
//        //未授权 被拒绝
//        self.powerBlock(PowerStateRefuse);
//    }else if(state == CBManagerStatePoweredOff){
//        //蓝牙未打开：app被允许使用蓝牙但是手机蓝牙已关闭
//        self.powerBlock(PowerStateBluetoothOff);
//    }else{
//        //蓝牙已打开
//        self.powerBlock(PowerStateAllow);
//    }
//}
/////蓝牙权限
//-(void)checkIsHavePower_Bluetooth:(void (^)(NSInteger status))allowBlock{
//    self.powerBlock = allowBlock;
////    [self.centralManager stopScan];
//    self.centralManager.state;
//PowerStateBluetoothResetting = 11,//蓝牙重置中，基本不会出现
//PowerStateBluetoothUnsupported = 12,//设备不支持蓝牙，基本不会出现
//PowerStateBluetoothOff = 13//蓝牙未打开
//}

///相册权限
-(void)checkIsHavePower_Photo:(void (^)(NSInteger status))allowBlock{
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusNotDetermined) {
        //第一次使用
        [self showSelectPowerAlert:allowBlock whichPower:2];
    }else if (status == PHAuthorizationStatusAuthorized){
        //允许
        allowBlock(PowerStateAllow);
    }else{
        //拒绝
        if(self.showRefuseAlert){
            [self showAlert:@"您尚未授予本应用使用相册的权限，请前往设置"];
        }
        allowBlock(PowerStateRefuse);
    }
}
///相机权限
-(void)checkIsHavePower_Camera:(void (^)(NSInteger status))allowBlock{
    ///读取设备授权状态
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if(authStatus == AVAuthorizationStatusNotDetermined) {
        //第一次使用
        [self showSelectPowerAlert:allowBlock whichPower:1];
    }else if(authStatus == AVAuthorizationStatusAuthorized){
        //允许
        allowBlock(PowerStateAllow);
    }else{
        //拒绝
        if(self.showRefuseAlert){
            [self showAlert:@"您尚未授予本应用访问相机权限，请前往设置"];
        }
        allowBlock(PowerStateRefuse);
    }
}
///通讯录
-(void)checkIsHavePower_Contacts:(void (^)(NSInteger status))allowBlock{
    // 判断是否授权
    CNAuthorizationStatus authorizationStatus  = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
    if (authorizationStatus == CNAuthorizationStatusNotDetermined) {
        //第一次使用
        [self showSelectPowerAlert:allowBlock whichPower:0];
    }else if (authorizationStatus == CNAuthorizationStatusAuthorized){
        //允许
        allowBlock(PowerStateAllow);
    }else{
        //拒绝
        if(self.showRefuseAlert){
            [self showAlert:@"您尚未授予本应用访问通讯录的权限，请前往设置"];
        }
        allowBlock(PowerStateRefuse);
    }
}
///麦克风
-(void)checkIsHavePower_Microphone:(void (^)(NSInteger status))allowBlock{
    if (@available(iOS 17.0, *)) {
        AVAudioApplication *audioSession = [AVAudioApplication sharedInstance];
        AVAudioApplicationRecordPermission authStatus = audioSession.recordPermission;
        if (authStatus == AVAudioApplicationRecordPermissionUndetermined) {
            //第一次使用
            [self showSelectPowerAlert:allowBlock whichPower:3];
        }else if(authStatus == AVAudioApplicationRecordPermissionGranted){
            //允许
            allowBlock(PowerStateAllow);
        }else{
            //拒绝
            if(self.showRefuseAlert){
                [self showAlert:@"您尚未授予本应用访问麦克风权限，请前往设置"];
            }
            allowBlock(PowerStateRefuse);
        }
    } else {
        //读取设备授权状态
        AVAudioSession *audioSession = [AVAudioSession sharedInstance];
        AVAudioSessionRecordPermission authStatus = audioSession.recordPermission;
        if (authStatus == AVAudioSessionRecordPermissionUndetermined) {
            //第一次使用
            [self showSelectPowerAlert:allowBlock whichPower:3];
        }else if(authStatus == AVAudioSessionRecordPermissionGranted){
            //允许
            allowBlock(PowerStateAllow);
        }else{
            //拒绝
            if(self.showRefuseAlert){
                [self showAlert:@"您尚未授予本应用访问麦克风权限，请前往设置"];
            }
            allowBlock(PowerStateRefuse);
        }
    }
}
-(void)showSelectPowerAlert:(void (^)(NSInteger status))allowBlock whichPower:(NSInteger)whichPower{
    switch (whichPower) {
        case 0:
        {
            // 联系人
            CNContactStore *store = [[CNContactStore alloc]init];
            [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    allowBlock(granted ? PowerStateAllow:PowerStateRefuse);
                });
            }];
        }
            break;
        case 1://相机
        {
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    allowBlock(granted ? PowerStateAllow:PowerStateRefuse);
                });
            }];
        }
            break;
        case 2://相册
        {
            [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if(status == PHAuthorizationStatusAuthorized) {
                        // 用户点击 "OK"
                        allowBlock(PowerStateAllow);
                    } else {
                        // 用户点击 不允许访问
                        allowBlock(PowerStateRefuse);
                    }
                });
                
            }];
        }
            break;
        case 3://麦克风
        {
            if (@available(iOS 17.0, *)) {
                [AVAudioApplication requestRecordPermissionWithCompletionHandler:^(BOOL granted) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        allowBlock(granted ? PowerStateAllow:PowerStateRefuse);
                    });
                }];
            }else{
                AVAudioSession *audioSession = [AVAudioSession sharedInstance];
                [audioSession requestRecordPermission:^(BOOL granted) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        allowBlock(granted ? PowerStateAllow:PowerStateRefuse);
                    });
                }];
            }
        }
            break;
            
        default:
            break;
    }
    
}
-(void)showAlert:(NSString *)alertStr{
    dispatch_async(dispatch_get_main_queue(), ^{
        UIAlertController *vc = [UIAlertController alertControllerWithTitle:nil message:alertStr preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"前往设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [vc dismissViewControllerAnimated:YES completion:nil];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:^(BOOL success) {
            }];
        }];
        if(self.refuseAlertShowCancel){
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            }];
            [vc addAction:cancelAction];
        }
        [vc addAction:sureAction];
        if ([self getCurrentVC]) {
            [[self getCurrentVC] presentViewController:vc animated:YES completion:nil];
        }
    });
}

//获取当前屏幕显示的viewcontroller
-(UIViewController *)getCurrentVC
{
    UIViewController *result = nil;
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    if ([nextResponder isKindOfClass:[UIViewController class]]){
        result = nextResponder;
    }else{
        result = window.rootViewController;
    }
    
    if ([result isKindOfClass:[UITabBarController class]]) {
        result = [(UITabBarController *)result selectedViewController];
    }
    if ([result isKindOfClass:[UINavigationController class]]) {
        result = [(UINavigationController *)result topViewController];
    }
    return result;
}

@end
